import type { Directive } from 'vue'

// 防抖指令
export const debounce: Directive = {
  mounted(el, binding) {
    const { value, arg } = binding
    const delay = arg ? parseInt(arg) : 300
    
    let timer: number | null = null
    
    el._debounceHandler = (event: Event) => {
      if (timer) {
        window.clearTimeout(timer)
      }
      
      timer = window.setTimeout(() => {
        if (typeof value === 'function') {
          value(event)
        }
      }, delay)
    }
    
    el.addEventListener('click', el._debounceHandler)
  },
  
  unmounted(el) {
    if (el._debounceHandler) {
      el.removeEventListener('click', el._debounceHandler)
      delete el._debounceHandler
    }
  }
}
